// Local Includes
#include "stdafx.h"
#include "MyFont.h"

// SDL Includes
#include <SDL_opengl.h>

// System Includes
#if defined(_WIN32)
#include <windows.h>
#else
#endif

#ifdef __APPLE_CC__
  #include <string.h>
#endif

MyFont::MyFont()
: _dlID(0),
  _aColor()
{
}

MyFont::~MyFont()
{
}

bool
MyFont::init( char* pChar, float *pCol )
{
    bool res = true;

    _aColor[0] = pCol[0];
    _aColor[1] = pCol[1];
    _aColor[2] = pCol[2];
    _aColor[3] = pCol[3];

#if defined(_WIN32)
    HDC hDC = wglGetCurrentDC();
    
    _dlID = glGenLists( (GLsizei)256 );
    
    if( _dlID == 0 )
        return false;

    LOGFONT sFont;
    
    sFont.lfHeight = -18;
    sFont.lfWidth = 0;
    sFont.lfEscapement = 0;
    sFont.lfOrientation = 0;
    sFont.lfWeight = FW_NORMAL;
    sFont.lfItalic = 0;
    sFont.lfUnderline = 0;
    sFont.lfStrikeOut = 0;
    sFont.lfCharSet = ANSI_CHARSET;
    sFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
    sFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
    sFont.lfQuality = DEFAULT_QUALITY;
    sFont.lfPitchAndFamily = FF_DONTCARE | DEFAULT_PITCH;

    HFONT hFont = ::CreateFontIndirect( &sFont );
    HFONT hOldFont = (HFONT)::SelectObject( hDC, hFont );

    res = (wglUseFontBitmapsA( hDC, 0, 256, _dlID ) == 1);

    ::SelectObject( hDC, hOldFont );
    ::DeleteObject( hFont );
#else
    // TOXIC: NYI
#endif

    return res;
}

bool 
MyFont::render( MyContext * pContext, char* pStr, int x, int y ) const
{
    // Early out if the font does not contain a display list
    if ( _dlID == 0 ) { return true; }

    // Ensure that OpenGL state is restored
    GLbitfield glAttribBits = GL_ENABLE_BIT   | 
                              GL_VIEWPORT_BIT | 
                              GL_DEPTH_BUFFER_BIT;
    glPushAttrib(glAttribBits);

    glColor4fv(_aColor);

    // Set our displaylist ID as the root
    glListBase(_dlID);

    // Ensure 2D Texturing is disabled
    glDisable( GL_TEXTURE_2D );
    
    // Set modelview to identity
    glMatrixMode( GL_MODELVIEW );
    glPushMatrix(); 
    glLoadIdentity();

    // Set projection to identity
    glMatrixMode( GL_PROJECTION );
    glPushMatrix();
    glLoadIdentity();

    // Set the text position
    glViewport( x, y, 1, 1 );
    glRasterPos2i( 0, 0 );

    glDisable( GL_BLEND );

    glCallLists((GLsizei)strlen(pStr),GL_UNSIGNED_BYTE,(const GLvoid*)(char*)pStr);

    glEnable( GL_BLEND );

    // Restore projection matrix
    glPopMatrix();

    // Restore model-view matrix
    glMatrixMode( GL_MODELVIEW );
    glPopMatrix();

    glPopAttrib();

    return true;
}